/**
   Copyright [Shan Yin]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.monkeydb.core;

import java.util.ArrayList;
import java.util.List;

public class MonkeyDB {
	private MemStore ms;
	private List<Store> sfiles;
	private MemCache cache;
	private MonkeyLog mlog;
	
	public void init(){
		ms = new MemStore();
		sfiles = new ArrayList<Store>();
		cache = new MemCache();
		mlog = new MonkeyLog();
	}

	public String get(String key) {
		KeyValue kv = cache.find(key);
		if (kv == null) {
			kv = ms.find(key);
			if (kv == null) {
				for (Store s : sfiles) {
					kv = s.find(key);
					if (kv != null) {
						break;
					}
				}
			}
		}
		if (kv != null) {
			return kv.getValue();
		} else {
			return null;
		}
	}

	public void set(String key, String value, long ttl) {
		KeyValue kv = new KeyValue();
		kv.setKey(key);
		kv.setValue(value);
		kv.setTTL(ttl);
		insert(kv);
	}

	public void delete(String key) {
		KeyValue kv = new KeyValue();
		kv.setKey(key);
		kv.setDeleted(true);
		insert(kv);
	}
	
	private void insert(KeyValue kv){
		mlog.record(kv);
		cache.put(kv);
		ms.put(kv);
	}
}
